package middleware

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog"
	"io"
	"net/http"
	"strings"
	"time"
)

func DefaultLogger(log zerolog.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		var params string
		if c.Request.Method == http.MethodGet {
			params = c.Request.URL.RawQuery
		} else {
			b, err := c.GetRawData()
			if err == nil {
				params = string(b)
			}
			c.Request.Body = io.NopCloser(bytes.NewBuffer(b))
			params = strings.ReplaceAll(params, "\r", "")
			params = strings.ReplaceAll(params, "\n", "")
			params = strings.ReplaceAll(params, " ", "")
		}

		c.Next()

		latency := time.Since(start)

		log.Debug().
			Str("clientIp", c.ClientIP()).
			Str("latency", fmt.Sprintf("%s", latency)).
			Str("status", fmt.Sprintf("%d", c.Writer.Status())).
			Str("protocol", c.Request.Proto).
			Str("method", c.Request.Method).
			Str("path", c.Request.URL.Path).
			Str("params", fmt.Sprintf("[%s]", params)).
			Send()

	}
}
